//
//  main.m
//  BlockTest
//
//  Created by wangrui on 13-11-1.
//  Copyright (c) 2013年 PPS. All rights reserved.
//

#import <Foundation/Foundation.h>

void blockTest1(){
    dispatch_block_t block;
    
    if (YES) {
        block = ^{
            printf("YES\n");
        };
    }
    else{
        block = ^{
            printf("NO\n");
        };
    }
    
    block();
}




void blockTest2() {
    
    char a = 'A';

    ^{
        printf("%c\n",a);
        
    }();
    
}


#pragma mark - test B
void exampleB_addBlockToArray(NSMutableArray *array) {
    
    char b = 'B';
    
    [array addObject:^{
         
         printf("%c\n",b);
         
     }];
}

void exampleB() {
    
    NSMutableArray *array = [NSMutableArray array];
    
    exampleB_addBlockToArray(array);
    
    void (^block)() = [array objectAtIndex:0];
    
    block();
}


#pragma mark - test D

typedef void (^dBlock)();

dBlock exampleD_getBlock() {
    
    //非arc下，编译报错，堆栈中的block不能返回。 不想变量
#if __has_feature(objc_arc)
    
    char d = 'D';
    
    return
    
    ^{
        
        printf("%c\n",d);
        
    };
    */
#endif
    
    return NULL;
}

void exampleD() {
    
    dBlock b = exampleD_getBlock();
    b();
}


#pragma mark - test E


void exampleE() {
    NSString *sting = @"string";
    
    dispatch_block_t bl;
    
    {
        void (^ blockA)(void) = [^{
            NSLog(@"A-%@",sting);
        } copy];

        bl = blockA;
        [blockA release]; //可发送多次release
        
        blockA(); //这时调用的时堆栈上的block,所以还能访问
        
    }
    
    //bl(); //bad access, 堆栈上的已经释放
    
    void (^ blockB)(void) = ^{
        NSLog(@"B-%@",sting);
    };
    
    [blockB release]; //__NSStackBlock__.  retain, release均没有用，copy有用
    blockB();
    
    void (^ blockC)(void) = ^{
        NSLog(@"C");
    };
    
    blockC(); //__NSGlobalBlock__. retain, release,copy 均没有用

}


#pragma mark - main

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        exampleE();
    }
    
    return 0;
}

